<template>
  <div class="app-container">
    <div class="filter-container">

      <el-form :model="listQuery" ref="filterForm">
        <el-row>
          <el-col :span="4">
            <el-form-item label-width="100px" label="二维码批次号" class="postInfo-container-item">
              <el-input v-model="listQuery.batch_num" autocomplete="off" placeholder="批次号"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="4" :offset="1">
            <el-form-item label="状态" class="postInfo-container-item" >
              <el-select v-model="listQuery.status" placeholder="请选择" clearable class="filter-item">
                <el-option   :key="1" label="开启" :value="1"/>
                <el-option  :key="2"  label="关闭" :value="0"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="7" :offset="1">
            <el-form-item label-width="80px" label="时间范围:" class="postInfo-container-item">
              <el-date-picker
                v-model="daterange"
                type="daterange"
                value-format="yyyy-MM-dd"
                align="right"
                unlink-panels
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                :picker-options="pickerOptions"
                @change="daterangeHandle">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
              查询
            </el-button>
          </el-col>
        </el-row>
      </el-form>
      <el-button type="primary" @click="handleAdd">生成二维码</el-button>

    </div>


    <el-table ref="dragTable" v-loading="listLoading" :data="list" row-key="id" fit highlight-current-row
              style="width: 100%;margin-top:30px;">
      <el-table-column align="center" label="批次号">
        <template slot-scope="scope">
          {{ scope.row.batch_num }}
        </template>
      </el-table-column>
      <el-table-column align="center" label="状态">
        <template slot-scope="scope">
          <el-button @click="handleStatus(scope)" type="success" size="mini" v-if="scope.row.status==1">开启</el-button>
          <el-button @click="handleStatus(scope)" type="warning" size="mini" v-if="scope.row.status==0">关闭</el-button>
        </template>
      </el-table-column>
      <el-table-column align="center" label="红包规格">
        <template slot-scope="scope">
          <div v-for="(item,key) in scope.row.specs">
          <span v-if="item>0"> 金额： {{item}} 元</span> <br>
          </div>
        </template>
      </el-table-column>
      <el-table-column align="center" label="箱数">
        <template slot-scope="scope">
          {{ scope.row.box_num}}
        </template>
      </el-table-column>
      <el-table-column align="center" label="生成时间">
        <template slot-scope="scope">
          {{ scope.row.create_time}}
        </template>
      </el-table-column>
      <el-table-column align="center" label="操作">
        <template slot-scope="scope">
          <el-button type="primary" size="mini" @click="handleView(scope)">
            查看
          </el-button>
          <el-button v-if="scope.row.is_created_cdkey==1" type="danger" size="mini" @click="handleDownLoad(scope)">下载</el-button>

        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit"
                @pagination="getList"/>
    <el-dialog :visible.sync="dialogVisible" :title="dialogType==='edit'?'编辑轮播图':'新增轮播图'">
      <el-form :model="data" label-position="left" label-width="120px">
        <el-form-item label="二维码批次号" required>
          <el-input v-model="data.batch_num" placeholder="二维码批次号" maxlength="8" show-word-limit
                    :disabled="dialogType=='edit'?true:false"/>
          <p>提示：仅用于方便管理二维码。相当于食品的批次号一样，可用于追溯和审查该批二维码的情况，批次号可以是数字、字母、-。</p>
        </el-form-item>
        <el-form-item label="状态" required >
          <el-radio v-model="data.status" :label="1">开启</el-radio>
          <el-radio v-model="data.status" :label="0">关闭</el-radio>
        </el-form-item>
        <el-form-item label="红包规格" style="margin-bottom: 30px;" required>
          <el-row   v-for="(item,key) in specs" >
            <el-col :span="6">
              <el-input v-model="specs[key]" :disabled="dialogType=='edit'?true:false"/>
            </el-col>
            <el-col :span="1">元</el-col>

          </el-row>
          <p>红包金额范围1-200元</p>
          <el-button  size="mini" @click="addGg" v-if="dialogType=='new'">添加规格</el-button>
        </el-form-item>
        <el-form-item label="箱数" required>
          <el-input v-model="data.box_num" placeholder="箱数"
                    :disabled="dialogType=='edit'?true:false"/>
        </el-form-item>
      </el-form>
      <div style="text-align:right;">
        <el-button type="danger" @click="dialogVisible=false">取消</el-button>
        <el-button type="primary" @click="saveData">保存</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
  import waves from '@/directive/waves' // waves directive

  import Pagination from '@/components/Pagination'
  import { addRedPacket, getDownTxt, getRedPacket, getRedPacketUrl, updateStatus } from '../../api/redPacket'

  const statusShow = {
    1: '已跟进',
    2: '未跟进'
  }
  export default {
    components: { Pagination },
    directives: { waves },

    filters: {
      statusFilter(status) {
        const statusMap = {
          2: 'info',
          1: 'success'
        }
        return statusMap[status] ?? 'danger'
      },
      statusShowFilter(status) {
        return statusShow[status] ?? '无'
      }
    },
    data() {
      return {
        pickerOptions: {
          shortcuts: [{
            text: '最近一周',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
              picker.$emit('pick', [start, end])
            }
          }, {
            text: '最近一个月',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
              picker.$emit('pick', [start, end])
            }
          }, {
            text: '最近三个月',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
              picker.$emit('pick', [start, end])
            }
          }]
        },
        statusShow,
        specs:[],
        daterange: [],
        data: {},
        list: [],
        dialogVisible: false,
        dialogType: 'new',
        total: 0,
        listLoading: true,
        listQuery: {
          page: 1,
          limit: 20
        }
      }
    },
    created() {
      this.getList()
    },
    methods: {
      addGg(){
        this.specs.push('')
      },
      saveData() {
        const param=this.data
        param.spec=this.specs.join(',')
        addRedPacket(param).then(res=>{
          this.$message.success('添加成功！')
           this.getList();
           this.dialogVisible=false
        })
      },
      handleAdd() {
        this.data = {}
        this.dialogVisible = true
        this.dialogType = 'new'
        this.specs=[]
      },
      daterangeHandle(value) {
        this.listQuery.begin_time = value[0]
        this.listQuery.end_time = value[1]
      },
      handleFilter() {
        this.listQuery.page = 1
        this.getList()
      },
      async getList() {
        this.listLoading = true
        const res = await getRedPacket(this.listQuery)
        this.list = res.data.data
        this.total = res.data.total
        this.listLoading = false
      },
      handleView(scope) {
        this.data = scope.row
        this.dialogVisible = true
        this.dialogType = 'edit'
        this.specs=this.data.specs
      },
      handleDownLoad({ $index, row }) {
        getDownTxt(row.id).then(res => {
          console.log(res)
          this.fileDownloadBlob(res.data,row.batch_num+'.txt')
        })
      },
      fileDownloadBlob(data, filename) {
        if (window.navigator.msSaveBlob) {
          let blobObject = new Blob([data]);
          window.navigator.msSaveBlob(blobObject, filename);
        } else {
          let url = window.URL.createObjectURL(new Blob([data]));
          let link = document.createElement("a");
          link.style.display = "none";
          link.href = url;
          link.setAttribute("download", filename);
          document.body.appendChild(link);
          link.click();
        }
      },
      handleStatus({ $index, row }) {
        updateStatus(row.id).then(res => {
          row.status=!row.status
        })
      }
    }
  }
</script>

<style lang="scss" scoped>
  .app-container {
    .roles-table {
      margin-top: 30px;
    }

    .permission-tree {
      margin-bottom: 30px;
    }
  }
</style>
